from common.database import db
from model.detect_result import DetectResult
from result.result import Result
from flask_jwt_extended import get_jwt_identity
from result.result_code import ResultCode
from utils.check_data import check_data


class DetectResultService(object):

    @staticmethod
    def results_to_response(results):
        results_list = []
        for item in results.items:
            results_list.append(item.to_dict())

        return {
            'total_pages': results.pages,
            'total_items': results.total,
            'current_page': results.page,
            'per_page': results.per_page,
            'detect_results': results_list
        }

    @staticmethod
    def selectAll(data):
        # if get_jwt_identity() != "2492655520@qq.com":
        #     return Result.error(ResultCode.FORBIDDEN, "您没有权限访问该接口")
        # print(data)
        # if not check_data(data, ["page", "per_page"]):
        #     return Result.error(ResultCode.DATA_ERROR.value, "必填项不可为空")
        detect_results = DetectResult.query.order_by(DetectResult.detect_time.desc()).paginate(page=data['page'], per_page=data['per_page'], error_out=False)
        return Result.success_data(DetectResultService.results_to_response(detect_results))

    @staticmethod
    def selectByUserEmail(data):
        detect_results = DetectResult.query.filter(DetectResult.user_email == get_jwt_identity()).paginate(page=data['page'], per_page=data['per_page'], error_out=False)
        return Result.success_data(DetectResultService.results_to_response(detect_results))